﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CanPower.Models;
using Microsoft.Extensions.Logging;
using NLog;
using System.Collections.ObjectModel;
using System.Windows.Input;
using static CanPower.Achieve.CANCommunitor;
using CanPower.Achieve;
using System.Windows.Documents;
using System.Windows.Controls;
using System.IO;
using System.Diagnostics;

namespace CanPower.Models
{
    public partial class MainViewModel:ObservableObject
    {
        public ICommand StartPowerCommand { get; }
        public ICommand ClosePowerCommand { get; }
        //public ObservableCollection<string> Logs { get; set; }
        public Logger Logger { get; private set; }
        private const uint DeviceType = 4; //设备类型（CANalyst-II 通常是 4）
        private const uint DeviceIndex = 0; //设备索引
        private const uint CanIndex = 0; //通道号
        //三个模块为一组
        [ObservableProperty]
        private int module1;
        [ObservableProperty]
        private int module2;
        [ObservableProperty]
        private int module3;
        public MainViewModel()
        {
            //Logs = new ObservableCollection<string>();
            Logger = Logger.GetInstance();
            StartPowerCommand = new RelayCommand(async () => await StartPowerAsync());
            ClosePowerCommand = new RelayCommand(async () => await ClosePowerAsync());
        }

        //打开设备
        [RelayCommand]
        private void OpenDevice()
        {
            if (CANCommunitor.OpenDevice())
            {
                Logger.WriteLog("设备启动失败");
            }
            else
            {
                Logger.WriteLog("设备启动成功");
            }
        }
        //初始化CAN通道
        [RelayCommand]
        private void InitChannel()
        {
            if (CANCommunitor.CANDeviceInit()) 
            {
                Logger.WriteLog("设备初始化失败");
            }
            else
            {
                Logger.WriteLog("设备初始化成功");
            }
            CANCommunitor.InitAllInfo();
        }
        //启动CAN
        [RelayCommand]
        private void CANStart()
        {
            if (StartCAN())
            {
                Logger.WriteLog("Can通信启动失败");
            }
            else
            {
                Logger.WriteLog("Can通信启动成功,各模块状态：");
                StartReceiving();
            }
        }

        //同时下发三个电源开启命令
        public async Task StartPowerAsync()
        {
            bool power = true;  //true为0x00开电源，false为0x01关电源
            
            ValueTask<bool> task1 = SetPower(Module1,power);
            ValueTask<bool> task2 = SetPower(Module2,power);
            ValueTask<bool> task3 = SetPower(Module3,power);

            // ValueTask中没有WhenAll方法，将 ValueTask 转换为 Task
            Task<bool> task1AsTask = task1.AsTask();
            Task<bool> task2AsTask = task2.AsTask();
            Task<bool> task3AsTask = task3.AsTask();

            // 获取结果
            bool[] results =await Task.WhenAll(task1AsTask, task2AsTask, task3AsTask);

            Logger.WriteLog($"电源模块{Module1}控制结果: {results[0]}");
            Logger.WriteLog($"电源模块{Module2}控制结果: {results[1]}");
            Logger.WriteLog($"电源模块{Module3}控制结果: {results[2]}");

            var powerStatusResultAfter = await GetPowerStatus();
            Logger.WriteLog("电源开启后各模块电源状态：------------------");
            for (int i = 0; i < powerStatusResultAfter.Length; i++)
            {
                Logger.WriteLog($"模块 {i + 1} 电源状态：{(powerStatusResultAfter[i] ? "开" : "关")}");
            }
        }

        //电源关闭命令
        public async Task ClosePowerAsync()
        {
            bool power = false;  //true为0x00开电源，false为0x01关电源
            
            ValueTask<bool> task1 = SetPower(Module1,power);
            ValueTask<bool> task2 = SetPower(Module2,power);
            ValueTask<bool> task3 = SetPower(Module3,power);

            // ValueTask中没有WhenAll方法，将 ValueTask 转换为 Task
            Task<bool> task1AsTask = task1.AsTask();
            Task<bool> task2AsTask = task2.AsTask();
            Task<bool> task3AsTask = task3.AsTask();

            // 使用 Task.WhenAll 等待所有任务完成
            await Task.WhenAll(task1AsTask, task2AsTask, task3AsTask);

            // 获取结果
            bool result1 = await task1;
            bool result2 = await task2;
            bool result3 = await task3;

            Logger.WriteLog($"电源模块{Module1}控制结果: {result1}");
            Logger.WriteLog($"电源模块{Module2}控制结果: {result2}");
            Logger.WriteLog($"电源模块{Module3}控制结果: {result3}");

            var powerStatusResultAfter = await GetPowerStatus();
            Logger.WriteLog("电源关闭后各模块电源状态：------------------");
            for (int i = 0; i < powerStatusResultAfter.Length; i++)
            {
                Logger.WriteLog($"模块 {i + 1} 电源状态：{(powerStatusResultAfter[i] ? "开" : "关")}");
            }
        }
        [RelayCommand]
        private void OpenLog()
        {
            string path = "D:\\Power\\Log";
            Process.Start("explorer",path);
        }

        //关闭设备
        [RelayCommand]
        private void CloseDevice()
        {
            if (VCI_CloseDevice(DeviceType, DeviceIndex) == 0)
            {
                Logger.WriteLog("设备关闭成功");
            }
            else
            {
                Logger.WriteLog("设备关闭失败");
            }
        }
        //清空日志
        [RelayCommand]
        private void CleanLog()
        {
            Logger.Clear();
        }



    }
}
